package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * @author MrZhao
 * @created 2025-10-12 22:49
 * @description 课程管理业务层实现类
 *
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> listBySubject(Integer subjectId) {
        return courseMapper.selectBySubject(subjectId);
    }

    @Override
    public List<Course> list() {
        return courseMapper.selectAll();
    }

    @Override
    public void updateById(CourseDTO dto) {
        // 参数校验
        boolean hasNullField = BeanUtil.hasNullField(dto, "description", "page", "pageSize");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        Course course = BeanUtil.copyProperties(dto, Course.class);
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.updateById(course);
    }

    @Override
    public Course getById(Integer id) {
        return courseMapper.selectById(id);
    }

    @Override
    public void deleteById(Integer id) {
        courseMapper.deleteById(id);
    }

    @Override
    public void add(CourseDTO dto) {
        // 参数校验
        boolean hasNullField = BeanUtil.hasNullField(dto,  "description", "id","page","pageSize");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        Course course = BeanUtil.copyProperties(dto, Course.class);
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public PageResult<Course> page(CourseDTO dto) {
        // 参数校验（略无需校验）
        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        // 查询
        List<Course> list = courseMapper.selectByPage(dto);
        // 封装分页结果
        Page<Course> page = (Page<Course>) list;
        return PageResult.<Course>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
